/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import domain.Invoice;
import domain.Mortgageconsumption;
import domain.Mortgagecontract;
import java.sql.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

/**
 *
 * @author Alejandro
 */
public class MortgageconsumptionDao {
    EntityManager em;
    EntityTransaction tx;

    public MortgageconsumptionDao() {
        em = SingletonDao.getInstance().getEntityManager();
        tx = SingletonDao.getTx();
    }

    public Mortgageconsumption getMortgageconsumption(Integer idM){
        Mortgageconsumption m = (Mortgageconsumption) em.createNativeQuery("select * from mortgageconsumption as m where m.idMortgageCons='"+idM+"'", Mortgageconsumption.class).getSingleResult();
        return m;
    }

    public void saveMortgageconsumption(Mortgageconsumption m){
        tx.begin();
        em.persist(m);
        tx.commit();
    }

    public void removeMortgageconsumption(Mortgageconsumption m){
        tx.begin();
        em.remove(m);
        tx.commit();
    }

    public List<Mortgageconsumption> getListCuota(Mortgagecontract m){
        List<Mortgageconsumption> list = em.createNativeQuery("select * from mortgageconsumption as m where m.mortgagecontractFK = '"+m.getIdMortgageContract()+"'").getResultList();
        return list;
    }

    public Mortgageconsumption getMortgageconsumptionDate(Mortgagecontract m){
        Mortgageconsumption ec = null;
        Date date = new Date(new java.util.Date().getTime());
        int month = date.getMonth();
        int year = date.getYear()+1900;
        int day = date.getDate();
        List list = em.createNativeQuery("select * from mortgageconsumption as e, contract as cont, consumption as cons where cont.idContract='"+m.getContract().getIdContract()+"' and  e.consFK=cons.idCons and cons.consFk=cont.idContract and e.dateTo>'"+year+"-"+month+"-"+day+"'", Mortgageconsumption.class).getResultList();
        if(!list.isEmpty()){
            ec = (Mortgageconsumption) list.get(0);
        }
        return ec;
    }

    public List<Mortgageconsumption> getMortgageListConsumption(Invoice i){
        List<Mortgageconsumption> l = em.createNativeQuery("select * from mortgageconsumption as mc where mc.invoiceFK ='"+i.getIdInvoice()+"'", Mortgageconsumption.class).getResultList();
        return l;
    }




}
